package com.tdam2011.grupo02.ui;

import java.util.LinkedList;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.connectivity.ConnectivityInformationSingleton;
import com.tdam2011.grupo02.data.DatabaseHelperSingleton;
import com.tdam2011.grupo02.data.LogsController;
import com.tdam2011.grupo02.data.OnSendingInterface;
import com.tdam2011.grupo02.domain.MensajeWeb;
import com.tdam2011.grupo02.widget.popup.ActionItem;
import com.tdam2011.grupo02.widget.popup.QuickAction;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class BandejaSalidaListFragment extends ListFragment implements
		OnClickDialogFragmentInterface, OnSendingInterface {

	private Context context;
	private MsgwCustomAdapter msgwsAdapter;
	private ListView msgwsListView;
	private QuickAction msgwsPopup;
	private OnItemClickListener msgwsItemClick;
	private int msgwsAdapterPosition;
	private MensajeWeb msgw;
	private LogsController controller;
	private MsgwBandejaSalidaAsyncTask mswsAsyncTask;

	private final static int POPUP_ACTION_ITEM_SEND = 11;
	private final static int POPUP_ACTION_ITEM_DELETE = 12;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setListShown(true);

		msgwsListView = getListView();

		msgwsAdapter = new MsgwCustomAdapter(context);
		msgwsListView.setAdapter(msgwsAdapter);
		msgwsListView.setOnItemClickListener(msgwsItemClick);

		msgwsListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				msgwsAdapterPosition = position;

				int firstPosition = getListView().getFirstVisiblePosition()
						- getListView().getHeaderViewsCount();
				int wantedChild = msgwsAdapterPosition - firstPosition;

				View v = (View) msgwsListView.getChildAt(wantedChild);
				msgwsPopup.show(v);

				return false;
			}
		});

		controller = new LogsController(context);
		createMsgwPopup();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		inflater.inflate(R.layout.log_web_messages, container);
		return super.onCreateView(inflater, container, savedInstanceState);
	}

	@Override
	public void onResume() {
		initData();

		super.onResume();
	}

	private void initData() {
		mswsAsyncTask = new MsgwBandejaSalidaAsyncTask();
		mswsAsyncTask.execute();
	}

	private LinkedList<MensajeWeb> getMsgwOutbox() {
		ContactDataInterface data = (ContactDataInterface) context;
		String nombreContacto = data.onDataSelected()[1];

		return controller.getWebMessagesOutboxByContact(nombreContacto);
	}

	private class MsgwBandejaSalidaAsyncTask extends
			AsyncTask<String, String, LinkedList<MensajeWeb>> {

		@Override
		protected LinkedList<MensajeWeb> doInBackground(String... arg0) {
			return getMsgwOutbox();
		}

		@Override
		protected void onPostExecute(LinkedList<MensajeWeb> result) {
			msgwsAdapter.add(result);
			msgwsAdapter.notifyDataSetChanged();

			super.onPostExecute(result);
		}
	}

	private void createMsgwPopup() {
		ActionItem eliminarItem = new ActionItem(POPUP_ACTION_ITEM_DELETE,
				getString(R.string.actionDelete), getResources().getDrawable(
						android.R.drawable.ic_menu_delete));

		ActionItem sendItem = new ActionItem(POPUP_ACTION_ITEM_SEND,
				getString(R.string.actionSend), getResources().getDrawable(
						android.R.drawable.ic_menu_send));

		msgwsPopup = new QuickAction(context);
		msgwsPopup.addActionItem(eliminarItem);
		msgwsPopup.addActionItem(sendItem);
		msgwsPopup
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(QuickAction quickAction, int pos,
							int actionId) {
						msgw = (MensajeWeb) msgwsAdapter
								.getItem(msgwsAdapterPosition);

						switch (actionId) {
						case POPUP_ACTION_ITEM_SEND:
							sendWebMessageOutbox();
							break;

						case POPUP_ACTION_ITEM_DELETE:
							showDialog();
							break;
						}

					}
				});

		msgwsPopup.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {
			}
		});
	}

	private void sendWebMessageOutbox() {
		if (ConnectivityInformationSingleton.getInstance(context)
				.getConnectivityInformation().isInternetConnectionAvailable()) {

			ContactActionControllerSingleton
					.getInstance(context)
					.getContactActionController()
					.sendMsgWebConnection(this, msgw.getContacto(),
							msgw.getMensaje(), true);
		}
	}

	// Dialog Fragment

	private void showDialog() {
		DialogFragment newFragment = MyAlertDialogFragment.newInstance(this,
				getString(R.string.attentionAlertDialogTitle),
				getString(R.string.deleteItemAlertDialogMessage));
		newFragment.show(getFragmentManager(), "dialog");
	}

	@Override
	public void doPositiveClick() {
		int num = DatabaseHelperSingleton.getInstance(context)
				.getDatabaseHelper().deleteMsgwItem(msgw);
		if (num != 0)
			initData();
	}

	@Override
	public void doNegativeClick() {
	}

	// Notifications

	@Override
	public void onSending() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSuccess() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onError() {
		// TODO Auto-generated method stub

	}
}
